package de.szut.traineeslife.db;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import de.szut.traineeslife.db.DataBaseHandler.Tables;

public class DBProvider extends ContentProvider {

	private static final int USER = 0;
	private static final int USER_ID = 1;
	private DataBaseHandler dbh;

	private static final UriMatcher mUriMatcher = buildUriMatcher();

	private static UriMatcher buildUriMatcher() {
		final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
		final String authority = ReportContract.CONTENT_AUTHORITY;

		matcher.addURI(authority, "users", USER);
		matcher.addURI(authority, "users/*", USER_ID);
		return matcher;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		int count = 0;
		SQLiteDatabase db = dbh.getWritableDatabase();
		count = db.delete(Tables.TABLE_REPORTS, selection, selectionArgs);
		db.close();

		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (mUriMatcher.match(uri)) {
		case USER_ID:
			return ReportContract.Report.CONTENT_ITEM_TYPE;
		case USER:
			return ReportContract.Report.CONTENT_TYPE;
		default:
			throw new UnsupportedOperationException("Unknown uri: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase db = dbh.getWritableDatabase();

		switch (mUriMatcher.match(uri)) {
        case USER:
        	db.insertOrThrow(Tables.TABLE_REPORTS, null, values);
        	getContext().getContentResolver().notifyChange(uri, null);
        	return de.szut.traineeslife.db.ReportContract.Report.buildLocationUri(values.getAsString(de.szut.traineeslife.db.ReportContract.Report.KEY_ID));
		default:
            throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
		
	}

	@Override
	public boolean onCreate() {
		dbh = new DataBaseHandler(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		final SQLiteDatabase db = dbh.getReadableDatabase();
		final SQLiteQueryBuilder builder = new SQLiteQueryBuilder();
		builder.setTables(Tables.TABLE_REPORTS);
		return builder.query(db, projection, selection, selectionArgs, null, null, sortOrder);
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		final SQLiteDatabase db = dbh.getWritableDatabase();
		return db.update(Tables.TABLE_REPORTS, values, selection, selectionArgs);
		
	}

}
